<?php
header('Content-Type: application/json');
Header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE');
header("Access-Control-Allow-Headers: Content-Type");
header('Access-Control-Allow-Origin:*');   //跨域

require './mysql_init.php';

//判断post的数据类型是否有异常
function is_str($email,$captcha){
    $flag=true;
    
    if(gettype($email) !== "string" || gettype($email)!== "string"){
        $flag=false;
    }
    
    if(!isEmail($email)){
        $flag=false;
    }
    return $flag;
}
//判断是否是邮箱
function isEmail($email) {
    // 邮箱地址的正则表达式
    $pattern = "/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/";
    
    // 使用preg_match函数进行匹配
    if (preg_match($pattern, $email)) {
        return true; // 符合邮箱格式
    } else {
        return false; // 不符合邮箱格式
    }
}
//判断邮箱与验证码是否对应，以及时间是否合理
function check_captcha($pdo,$user_uid,$captcha){
    try {
        // 准备查询语句
        $query = "SELECT captcha_login_email_time FROM login WHERE captcha_login_email = ? AND user_uid=?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $captcha);
        $statement->bindParam(2, $user_uid);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['captcha_login_email_time'];      //把查询结构赋值给$result
        // 根据结果判断是否存在
        if (getTimeDifferenceInSeconds($result)< 60 && strtotime($result) >0) {
            return 1; // 成功
        }else if(getTimeDifferenceInSeconds($result) > 60 && strtotime($result)>0){
            return 2;  //验证码过期
        }else{
            return 0;
        }
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//输入字符串时间，返回字符串时间与当前时间的差
function getTimeDifferenceInSeconds($strTime) {
    // 字符串时间转换为时间戳
    $timestamp = strtotime($strTime);

    date_default_timezone_set("PRC");     //设置时区，PRC是中国人民共和国
    
    // 获取当前时间戳
    $currentTimestamp = time();
    
    // 计算时间差
    $timeDiff = $currentTimestamp-$timestamp;
    
    // 返回时间差（秒）
    return $timeDiff;
}
//查询邮箱的uid
function get_uid($pdo,$email){
    try {
        // 准备查询语句
        $query = "SELECT uid FROM users WHERE email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['uid'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//获取用户昵称
function getusername($pdo,$email){
    try {
        // 准备查询语句
        $query = "SELECT name FROM users WHERE email=?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['name'];      //把查询结构赋值给$result
        // 返回用户昵称
        return $result;
        
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return 0; // 表示查询出错
    }
}
//判断是否登录过
function is_have_session($pdo,$email){
    try {
        // 准备查询语句
        $query = "SELECT count(*) FROM session WHERE email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['count(*)'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
//把邮箱和Session_id插入到session表中
function insert_session_id($pdo,$email,$session_id){
    try {
        $captcha_login_email_n=0;
        $captcha_login_email_time='2000-10-08 10:07:56';
        // 准备插入语句并绑定参数
        $query = "INSERT INTO session(email,session_id) values(?,?)";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        $statement->bindParam(2, $session_id);
        // 执行插入操作
        $statement->execute();
        return 1;
        // echo "Data inserted successfully.";
    } catch (PDOException $e) {
        // echo "Error inserting data: " . $e->getMessage();
        return 0;
    }
}
//更新session_id
function update_session_id($pdo,$email,$session_id) {
    try {
        // 准备插入语句并绑定参数
        $query = "UPDATE session set email=?,session_id=? where email=?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        $statement->bindParam(2, $session_id);
        $statement->bindParam(3, $email);
        
        // 执行插入操作
        $statement->execute();
        return 1;
        // echo "Data inserted successfully.";
    } catch (PDOException $e) {
        // echo "Error updata data: " . $e->getMessage();
        return 0;
    }
}
//判断是否是商家,返回1表示是商家，返回0表示是普通用户
function is_seller($pdo,$email){
    try {
        // 准备查询语句
        $query = "SELECT is_seller FROM users WHERE email = ?";
        $statement = $pdo->prepare($query);
        $statement->bindParam(1, $email);
        // 执行查询
        $statement->execute();
        // 获取结果
        $result = $statement->fetchAll()[0]['is_seller'];      //把查询结构赋值给$count
        return $result;
    } catch (PDOException $e) {
        // 异常处理
        echo "Error querying database: " . $e->getMessage();
        return -1; // 表示查询出错
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {    //是post请求
    // 检查是否接收到账号和密码
    $response = array(     //初始化
        'status' => 0,
        'message' => '进入post',
        'seeeion_id'=>'',
        'usernmae'=>'',
        'is_seller'=>''
    );
    $json=file_get_contents('php://input');  //获取post请求中的原始数据
    $post_json=json_decode($json,true);       //把原始数据转化成json

    $email=$post_json['user_email'];
    $captcha=$post_json['user_captcha'];

    if (is_str($email,$captcha)) {      //判断post数据是否异常
        $user_uid=get_uid($pdo,$email);
        
        if(check_captcha($pdo,$user_uid,$captcha) === 1 ){  //密码和验证码校http://localhost:8080/#/user验码都符合,对验证码同等加密，达到与校验码一致
            session_start();
            $session_id=session_id();
            $response = array(
                'status' => 1,
                'message' => '登录成功',
                'seeeion_id'=>$session_id,
                'usernmae'=>getusername($pdo,$email),
                'is_seller'=>is_seller($pdo,$email)
            );
            if(is_have_session($pdo,$email)==0){
                insert_session_id($pdo,$email,$session_id);
            }else{
                update_session_id($pdo,$email,$session_id);
            }
        }else if(check_captcha($pdo,$user_uid,$captcha) === 2){
            $response = array(
                'status' => 0,
                'message' => '验证码过期',
                'seeeion_id'=>'',
                'usernmae'=>'',
                'is_seller'=>''
                );
        }else{
            $response = array(
                'status' => 0,
                'message' => '验证码错误',
                'seeeion_id'=>'',
                'usernmae'=>'',
                'is_seller'=>''
                );
        }     
    } else {      //提交的数据异常
        $response = array(
            'status' => 0,
            'message' => '未提供账号或密码',
            'seeeion_id'=>'',
            'usernmae'=>'',
            'is_seller'=>''
        );
    }
    echo json_encode($response);
}else{   //非post
    $response = array(
        'status' => 0,
        'message' => '不是post',
        'seeeion_id'=>'',
        'usernmae'=>'',
        'is_seller'=>''
    );
    echo json_encode($response);
}
?>